<template>
  <div class="todo">
    <div class="list">
      <div style="padding: 0 10px 10px;">
        <a-input-search
          v-model="keyword"
          :placeholder="$t('all.autotext1712')"
          style="width: 100%"
          @search="onSearch"
        />
      </div>
      <div class="list-wrap">
        <div
          class="list-item"
          :class="{ 'active': selectId === item.proNo }"
          v-for="item in proList"
          :key="item.proNo"
          @click="proChange(item)"
        >
          {{ item.proNo === '-1' ? $t('all.autotext1711') : item.proNo }} ({{ item.count }})
        </div>
      </div>
    </div>
    <div class="table">
      <s-table
        ref="table"
        size="default"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{x: 'max-content'}"
      >
        <span slot="operation" slot-scope="text, record">
          <a @click="clickDetail(record)">{{ type === '0' ? $t('all.autotext1696') : $t('all.autotext568') }}</a>
        </span>
        <span
          class="content-title"
          slot="contentTitle"
          slot-scope="text"
          :title="text"
        >
          {{ text }}
        </span>
        <span slot="createTime" slot-scope="text, record">{{ record.createTime | moment }}</span>
        <span slot="costStatus" slot-scope="text">{{ text | enumValueByKey($const.EXAMINE_TYPE) }}</span>
        <span slot="auditStatus" slot-scope="text">{{ text === 1 ? $t('all.autotext249') : $t('all.autotext1710') }}</span>
      </s-table>
    </div>
    <!-- 意见反馈弹窗 -->
    <feedModal
      v-if="showFeedDetailModal"
      ref="feedRef"
      @ok="refresh"
      @close="showFeedDetailModal = false"
    />
    <feedCenterModal
      v-if="showFeedcenterModal"
      ref="feedCenterRef"
      @ok="refresh"
      @close="showFeedcenterModal = false"
    />
    <DetailView
      :type="1"
      @refresh="refresh"
      @closeCallback="closeCallback"
      @openPopup="openPopup"
      @payRecord="handlePayRecord"
      ref="detailView"
      :visible="feeVisible"
      :costId="costId"
    />
    <AuditFailure
      :visible="visibles"
      @uploadModalCancel="visibles = false"
      @uploadClickConfirm="uploadClickConfirm"
      :auditStatus="auditStatus"
      ref="AuditFailure"
    />
    <Approve v-model="oveVisibles" :auditStatus="auditStatus" @ok="approveOk" />
    <!-- 预算调整弹窗 -->
    <ViewBudget
      ref="budgetRef"
      :is-audit="isAudit"
      :viewType="viewType"
      :handType="handType"
      @handleOk="refresh"
    />
    <!-- 入账管理 -->
    <examineModal ref="examineRef" @refresh="refresh" />
  </div>
</template>

<script>
import { buildPaginationObj } from '@/components/Table'
import { listTodoByPage, listProNoTodo } from '@/api/system/message'
import { costRecordPay, switchAudit, preCheckForFinanceAudit } from '@/api/cost/audit'
import feedModal from '@views/feedback/components/feedModal'
import feedCenterModal from '@views/feedcenter/components/feedModal'
import DetailView from '@/views/cost-auditing/detail.vue'
import AuditFailure from '@/views/cost-auditing/components/auditFailure'
import Approve from '@/views/cost-auditing/components/approve'
import ViewBudget from '@views/overview/detail/treasurer/components/budget/viewBudget'
import examineModal from '@views/entry/components/examineModal'

export default {
  components: {
    feedModal,
    DetailView,
    AuditFailure,
    Approve,
    feedCenterModal,
    ViewBudget,
    examineModal
  },
  props: ['type', 'queryParam'],
  data () {
    return {
      applyNo: '',
      oldStatus: '',
      keyword: '',
      columns: [
        {
          title: this.$t('all.autotext818'),
          dataIndex: 'title',
          width: '300px',
          scopedSlots: { customRender: 'contentTitle' }
        },
        {
          title: this.$t('all.autotext1911'),
          dataIndex: 'ptsNo',
          width: '120px'
        },
        {
          title: this.$t('all.autotext1912'),
          dataIndex: 'researchCenterNo',
          width: '100px'
        },
        {
          title: this.$t('all.autotext1913'),
          dataIndex: 'proNo',
          width: '100px'
        },
        {
          title: this.$t('all.autotext1692'),
          dataIndex: 'applyNo'
        },
        {
          title: this.$t('all.autotext666'),
          dataIndex: 'createTime',
          minWidth: '200px',
          scopedSlots: { customRender: 'createTime' }
        },
        {
          title: this.$t('all.autotext505'),
          dataIndex: 'costStatus',
          minWidth: '100px',
          scopedSlots: { customRender: 'costStatus' }
        },
        {
          title: this.$t('all.autotext1697'),
          dataIndex: 'auditStatus',
          minWidth: '100px',
          scopedSlots: { customRender: 'auditStatus' }
        },
        {
          title: this.$t('all.autotext187'),
          dataIndex: 'operation',
          width: '70px',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      proList: [],
      selectId: null,
      loadData: parameter => {
        if (!this.selectId) return Promise.resolve(buildPaginationObj([]))
        return listTodoByPage(Object.assign(parameter, this.queryParam, { auditStatus: this.type, proNo: this.selectId }))
          .then(res => {
            return res.page
          })
      },
      showFeedDetailModal: false,
      showFeedcenterModal: false,
      // 费用审批弹窗
      feeVisible: false,
      costId: null,
      visibles: false,
      auditStatus: {},
      oveVisibles: false,
      viewType: '',
      handType: '',
      isAudit: true
    }
  },
  watch: {
    type (val) {
      this.getProlist()
    }
  },
  mounted () {
    this.getProlist()
  },
  methods: {
    async getProlist (e) {
      this.keyword = e || ''
      const res = await listProNoTodo({
        ...this.queryParam,
        auditStatus: this.type,
        proNo: e
      })
      this.$emit('countBack', {
        todoCount: res.todoCount,
        completedCount: res.completedCount
      })
      this.proList = res.list
      this.selectId = res.list.length ? res.list[0].proNo : null
      this.$refs.table.refresh(true)
    },
    refresh () {
      this.getProlist()
    },
    onSearch (e) {
      this.getProlist(e)
    },
    proChange (item) {
      this.selectId = item.proNo
      this.$refs.table.refresh(true)
    },
    clickDetail (record) {
      record.todoType = 9
      console.log(record)
      if (record.todoType === 1) {
        // 意见反馈
        if (this.$store.getters.userInfo.isAdmin === 1) {
          this.showFeedcenterModal = true
          this.$nextTick(() => (
            this.$refs.feedCenterRef.open(record.todoId)
          ))
        } else {
          this.showFeedDetailModal = true
          this.$nextTick(() => (
            this.$refs.feedRef.open(record.todoId)
          ))
        }
      } else if (record.todoType === 2) {
        if (this.type === '0') {
          this.handType = 'examine'
          this.isAudit = true
        } else {
          this.handType = 'view'
          this.isAudit = false
        }
        if (record.budgetFlag === 1) {
          // 如果是新增预算
          this.viewType = 'addBudget'
        } else {
          // 如果是预算调整
          this.viewType = 'adjustBudget'
        }
        this.$refs.budgetRef.open(record.todoId, record.projectId, record.proInfo.classify)
      } else if (record.todoType === 6) {
        // 如果是入账审批
        this.$refs.examineRef.open(record.todoId, record.todoStatus ? 2 : 1)
        // 如果是已注销 crc和pi可直接跳转到注销受试者页面
      } else if (record.todoType === 9) {
        this.$router.push('/subject-manage-cancelList')
      }  else if (record.todoType === 3 ||  record.costId) {
        if (record.refuseOrRevokeFlag) {
          this.$store.dispatch('EnterProject', record.proInfo).then(e => {
            this.$router.push({
              name: 'ApplyDetail',
              query: {
                id: record.costId,
                status: record.costStatus
              }
            })
          })
          return
        }
        // 如果是费用审核
        this.costId = record.costId
        this.feeVisible = true
      } else {
        this.$message.warning(this.$t('all.autotext352'))
      }
    },
    // 打开审核弹窗
    async openPopup (value) {
      console.log(value)
      if (value.status === 1) {
        this.auditStatus = value
        this.oveVisibles = true
        return
      }
      if (value.status === true && this.$store.getters.roles[0]?.code === 'SYS_FINANCE') {
        const check = await preCheckForFinanceAudit({ feeApplyId: value.id })
        if (check.flag) {
          const that = this
          this.$confirm({
            title: this.$t('all.autotext730'),
            content: (h) => {
              return h('div', check.message.map(node => h('p', node)))
            },
            onOk () {
              that.handleSure(value)
            }
          })
        } else {
          this.handleSure(value)
        }
        return
      }
      this.handleSure(value)
    },
    handleSure (value) {
      this.applyNo = value.applyNo
      this.oldStatus = value.oldStatus
      this.auditStatus = value
      this.visibles = true
    },
    // 弹窗关闭回调
    closeCallback () {
      this.feeVisible = false
    },
    // 支付记录回调
    handlePayRecord () {
      this.$refs.detailView.payLoading = true
      costRecordPay({ id: this.costId, applyNo: this.applyNo }).then(res => {
        this.$refs.detailView.payLoading = false
        this.$message.success(this.$t('all.autotext470'))
        this.closeCallback()
        this.uploadModalCancel()
      }).catch(_ => {
        this.$refs.detailView.payLoading = false
      })
    },
    // 审核弹窗关闭回调
    uploadModalCancel () {
      this.visibles = false
      this.oveVisibles = false
    },
    // 审核弹窗确认回调
    uploadClickConfirm (value) {
      const status = value.status === true ? 1 : -1
      this.$refs.AuditFailure.confirmLoading = true
      switchAudit({ id: value.id, status: status, applyNo: this.applyNo, oldStatus: this.oldStatus, refuseReason: value.refuseReason, comment: value.comment, auditArray: value.auditArray.length ? JSON.stringify(value.auditArray) : undefined })
        .then((res) => {
          this.refresh()
          this.$refs.AuditFailure.confirmLoading = false
          this.$refs.AuditFailure.form = {}
          this.$message.success(this.$t('all.autotext470'))
          this.closeCallback()
          this.uploadModalCancel()
        })
        .catch(() => {
          this.$refs.AuditFailure.confirmLoading = false
        })
    },
    approveOk () {
      this.visibles = false
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>
.todo {
  display: flex;
  align-items: stretch;
  gap: 10px;
  .list {
    width: 170px;

    background: #fafafa;
    padding: 10px 0;
    overflow: hidden;
    .list-wrap {
      height: 600px;
      overflow-y: auto;
      .list-item {
        padding: 8px;
        transition: .2s;
        cursor: pointer;
        &:hover {
          background: #E6F7FF;
        }
      }
      .active {
        background: var(--var-primary-color);
        color: #fff;
        &:hover {
          background: var(--var-primary-color);
        }
      }
    }
  }
  .table {
    flex: 1;
  }
}
</style>
